package main

import (
	"context"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/text/gregex"
	"strconv"
	"strings"
)

func main() {
	ctx := context.Background()
	PanicIgnoreIndex(ctx, func(ctx context.Context) {
		_, err := g.DB().Exec(ctx, "INSERT INTO `vip_extends`(`product_id`,`quota`,`expired_at`,`created_at`,`updated_at`,`type`,`relation_type`,`relation_id`)VALUES(492,0,'0001-01-01 00:00:00','2023-02-09 06:55:28','2023-02-09 06:55:28',1,55578422)")
		if err != nil {
			panic(err)
		}
	})
}

func PanicIgnoreIndex(ctx context.Context, try func(ctx context.Context)) {
	defer func() {
		if exception := recover(); exception != nil {
			if v, ok := exception.(error); ok {
				if gerror.Code(v) == gcode.CodeDbOperationError {
					matches, err := gregex.MatchString(`Error (\d+)`, v.Error())
					if err == nil {
						code := matches[1]
						if code != "1062" {
							panic(err)
						}
					}
				}
			}
		}
	}()

	try(ctx)
}

func FormatVersionNumber(versionNo string) int {
	if versionNo == "" {
		return -1
	}

	nos := strings.Split(versionNo, ".")
	if len(nos) != 3 {
		return -1
	}

	no := 0

	for i, n := range nos {
		j, err := strconv.Atoi(n)
		if err != nil || j >= 100 || j < 0 {
			return -1
		}
		no += j * int(pow(100, (2-i)))
	}

	return no
}

func pow(x int, n int) int {
	if x == 0 || n < 0 {
		return 0
	}

	if n == 0 {
		return 1
	}

	result := 1

	for i := 0; i < n; i++ {
		result *= x
	}

	return result
}
